package com.suda.sudaexamsystem.service.impl;

import com.suda.sudaexamsystem.mapper.*;
import com.suda.sudaexamsystem.pojo.Clazz;
import com.suda.sudaexamsystem.pojo.ExamPaper;
import com.suda.sudaexamsystem.pojo.Notice;
import com.suda.sudaexamsystem.pojo.User;
import com.suda.sudaexamsystem.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private UserClazzMapper userClazzMapper;
    @Autowired
    private RequestMapper requestMapper;
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ExamPaperMapper examPaperMapper;
    @Autowired
    private NoticeUserMapper noticeUserMapper;

    @Override
    @Transactional
    public void createClazz(Clazz clazz) {
        clazzMapper.createClazz(clazz);
        userClazzMapper.addUserToClazz(clazz.getOwner(), clazz);
    }

    @Override
    @Transactional
    public void deleteClazz(int clazzId) {
        // 生成公告 告知相关用户 班级解散
        Clazz clazz = clazzMapper.findById(clazzId);
        Notice notice = new Notice();
        notice.setUser(clazz.getOwner());
        notice.setPublishTime(new Date());
        notice.setTitle("解散班级");
        notice.setContent(clazz.getName() + "已经被" + clazz.getOwner().getName() + "解散了");
        noticeMapper.publishNotice(notice);
        // 设置用户可见
        noticeUserMapper.addUserToVisitBatch(userMapper.findUsersByClazzId(clazzId), notice.getId());
        userClazzMapper.deleteClazzForAllUser(clazzId);
        clazzMapper.deleteClazz(clazzId);
        // 删除关于班级的试卷
        examPaperMapper.deleteByClazzId(clazzId);
    }

    @Override
    @Transactional
    public void addUserToClazz(User user, Clazz clazz) {
        // 已存在就不用再加入教室了
        if (!userClazzMapper.isUserInClazz(user.getId(), clazz.getId())) {
            userClazzMapper.addUserToClazz(user, clazz);
            // 删除申请记录
            requestMapper.deleteApplyRequest(user.getId(), clazz.getId());
        }
    }

    @Override
    @Transactional
    public Clazz findById(int clazzId) {
        return clazzMapper.findById(clazzId);
    }

    @Override
    @Transactional
    public List<Clazz> findByUserId(int userId) {
        return clazzMapper.findByUserId(userId);
    }

    @Override
    @Transactional
    public List<Clazz> findOwnerClazzByUserId(int userId) {
        return clazzMapper.findOwnerClazzByUserId(userId);
    }

    @Override
    @Transactional
    public List<Clazz> findAll() {
        return clazzMapper.findAll();
    }

    @Override
    @Transactional
    public void updateClazz(Clazz clazz) {
        // 更新用户和班级关系 班级所有者转让
        clazzMapper.updateClazz(clazz);
    }
}
